package com.bdqn.controller;

import com.bdqn.constant.Constant;
import com.bdqn.pojo.PageSupport;
import com.bdqn.pojo.Supplier;
import com.bdqn.service.SupplierService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/supplier")
public class SupplierController {
    private Logger logger = Logger.getLogger(SupplierController.class);

    @Resource
    private SupplierService supplierService;

    @RequestMapping("/list")
    public String getList( Model model, HttpServletRequest request,@RequestParam(required = false) String supCode, @RequestParam(required = false) String supName,@RequestParam(defaultValue = "1") Integer pageIndex){
        logger.info("进入supplier获取list方法");
        List<Supplier> supplierList = null;
        try{
            //设置页面容量
            int pageSize = Constant.pageSize;
            //总数量(表)
            int totalCount = supplierService.getSupplierCount(supCode,supName);
            //总页数
            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount = pages.getTotalPageCount();
            //控制首页和尾页
            if (pageIndex > totalPageCount){
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            supplierList = supplierService.getSupplier(supCode,supName,pageIndex,pageSize);
            model.addAttribute("supplierList",supplierList);
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("totalCount", pages.getTotalCount());
            model.addAttribute("currentPageNo",pages.getCurrentPageNo());
        }catch (Exception e){
            e.printStackTrace();
            logger.error("用户列表接口访问失败");
        }
        return "supplier/list";
    }
}
